package com.waiter.moximoxi;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.waiter.moximoxi.adapter.MainMenuAdapter;
import com.waiter.moximoxi.base.BaseActivity;
import com.waiter.moximoxi.bean.MainMessageBean;
import com.waiter.moximoxi.bean.MainTableListBean;
import com.waiter.moximoxi.constant.Constant;
import com.waiter.moximoxi.dialog.ManagerAreaDialog;
import com.waiter.moximoxi.dialog.MessageDialog;
import com.waiter.moximoxi.dialog.SendingOrderDialog;
import com.waiter.moximoxi.net.API;
import com.waiter.moximoxi.ui.LoginActivity;
import com.waiter.moximoxi.ui.SettlementActivity;
import com.waiter.moximoxi.utils.JsonTwoUtils;
import com.waiter.moximoxi.utils.XunFeiUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.OnClick;
import cn.yhong.aframework.listener.OkHttpSuccessListener;
import cn.yhong.aframework.listener.OnCallbackListener;
import cn.yhong.aframework.utils.AtyUtils;
import cn.yhong.aframework.utils.MyOkHttpUtils;
import cn.yhong.aframework.utils.SpUtils;
import cn.yhong.aframework.view.IBaseView;
import okhttp3.Call;

public class MainActivity extends BaseActivity implements View.OnClickListener, OnRefreshListener {

    @Bind(R.id.smartrefreshlayout)
    SmartRefreshLayout smartrefreshlayout;
    @Bind(R.id.manager_area)
    TextView manager_area;
    @Bind(R.id.login_out)
    TextView login_out;
    @Bind(R.id.main_grid)
    GridView main_grid;

    private MainMenuAdapter mainMenuAdapter;
    private List<MainTableListBean> mainMenuBeans;

    private ManagerAreaDialog managerAreaDialog;
    private MessageDialog messageDialog;
    private SendingOrderDialog sendingOrderDialog;
    private List<String> message_list;
    private String area_id;

    private XunFeiUtils xunFeiUtils;

    @Override
    public void initContent(Bundle savedInstanceState) {
        setContent(R.layout.activity_main);
    }

    @Override
    public void initView() {

        smartrefreshlayout.setOnRefreshListener(this);
        smartrefreshlayout.setDisableContentWhenRefresh(true);

        // 广播监听
        if (broadcastManager == null) {
            broadcastManager = LocalBroadcastManager.getInstance(this);
        }
        if (intentFilter == null) {
            intentFilter = new IntentFilter();
        }
        intentFilter.addAction(ACTION_RECIVE_NEWRED);
        if (receiver == null) {
            receiver = new MyActivityReceiver();
        }
        broadcastManager.registerReceiver(receiver, intentFilter);

        xunFeiUtils = new XunFeiUtils(mActivity);

        mainMenuBeans = new ArrayList<>();
        message_list = new ArrayList<>();
    }

    @Override
    public void initData() {
        ///消息弹框
        messageDialog = new MessageDialog(mActivity, new OnCallbackListener() {
            @Override
            public void onCallback(int type, Object... obj) {
                MainMessageBean mainMessageBean = (MainMessageBean) obj[0];
                if (mainMessageBean.state.equals("请求结账")) {
                    requestFinishOrder(mainMessageBean.table_sn);
//                    startActivityForResult(new Intent(mActivity, SettlementActivity.class).putExtra("order_sn", mainMessageBean.table_sn), 100);
                } else {
                    callSuccess(mainMessageBean.table_sn);
                }
            }
        });

        ///账单明细
        sendingOrderDialog = new SendingOrderDialog(mActivity, new OnCallbackListener() {
            @Override
            public void onCallback(int type, Object... obj) {
                if (type == 0) {
                    String order_sn = (String) obj[0];
                    if (order_sn != null) {
                        requestFinishOrder(order_sn);
                    }
                } else {
                    sendConfirm((String) obj[0]);
                }
            }
        });
        ///地区选择弹框
        managerAreaDialog = new ManagerAreaDialog(mActivity, new OnCallbackListener() {
            @Override
            public void onCallback(int type, Object... obj) {
                area_id = (String) obj[0];
                getTableList();
            }
        });

        mainMenuAdapter = new MainMenuAdapter(mActivity, mainMenuBeans);
        main_grid.setAdapter(mainMenuAdapter);

        main_grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //为3的时候说明是已开台状态
                if (mainMenuBeans.get(position).status == 3) {
                    sendingOrderDialog.showSendDialog(mainMenuBeans.get(position).id);
                }
//                else if (mainMenuBeans.get(position).status == 5) {//挂单状态
//                    sendingOrderDialog.showSendDialog(mainMenuBeans.get(position).id);
//                }
            }
        });
    }

    /**
     * 请求结账
     */
    private void requestFinishOrder(String table_sn) {
        Map<String, String> params = API.getParams();
        params.put("order_sn", table_sn);
        OkHttpUtils.post()
                .url(API.request_finish_order)
                .params(params)
                .headers(API.getHeads(mActivity))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        AtyUtils.showShort(mActivity, "网络异常，请稍后再试", false);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        if (API.filterJson(response)) {
                            startActivityForResult(new Intent(mActivity, SettlementActivity.class).putExtra("order_sn", table_sn), 100);
                        } else {
                            API.showMsg(mActivity, response);
                        }
                    }
                });
    }

    /**
     * 呼叫确认
     */
    private void callSuccess(String table_sn) {
        Map<String, String> params = API.getParams();
        params.put("order_sn", table_sn);
        MyOkHttpUtils.post_CallBack(API.true_call_waiter, params, API.getHeads(mActivity), new OkHttpSuccessListener(
                (IBaseView) mActivity, "呼叫确认成功", 3) {
            @Override
            public void onSuccessResponse(String response) {
                if (API.filterJson(response)) {
                    if (messageDialog != null && !messageDialog.isShowing()) {
                        if (message_list.size() > 0) {
                            String extra = message_list.get(0);
                            message_list.remove(extra);
                            showMessageDialog(extra);
                        }
                    }
                }
            }

            @Override
            public void onErrorResponse() {
                AtyUtils.showShort(mActivity, "网络异常，请稍后再试", false);
            }
        });
    }

    /**
     * 获取餐桌列表
     */
    private void getTableList() {
        Map<String, String> params = API.getParams();
        params.put("id", area_id + "");
        MyOkHttpUtils.post_CallBack(API.table_list, params, API.getHeads(mActivity), new OkHttpSuccessListener(
                (IBaseView) mActivity, "餐桌列表", 2) {
            @Override
            public void onSuccessResponse(String response) {
                if (smartrefreshlayout != null) {
                    smartrefreshlayout.finishRefresh();
                }
                mainMenuBeans.clear();
                if (API.filterJson(response)) {
                    List<MainTableListBean> mainTableListBeans = JsonTwoUtils.parseListJson(response, MainTableListBean.class);
                    if (mainTableListBeans != null && mainTableListBeans.size() > 0) {
                        mainMenuBeans.addAll(mainTableListBeans);
                    }
                    mainMenuAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onErrorResponse() {
                if (smartrefreshlayout != null) {
                    smartrefreshlayout.finishRefresh();
                }
                AtyUtils.showShort(mActivity, "网络异常，请稍后再试", false);
            }
        });
    }

    @OnClick({R.id.manager_area, R.id.login_out})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.manager_area://管理区域
                managerAreaDialog.showSetDatas();
                break;
            case R.id.login_out://退出登录
                LoginOut();
                break;
        }
    }

    /**
     * 确认送达
     *
     * @param salt
     */
    private void sendConfirm(String salt) {
        Map<String, String> params = API.getParams();
        params.put("salt", salt);
        MyOkHttpUtils.post_CallBack(API.true_send, params, API.getHeads(mActivity), new OkHttpSuccessListener(
                (IBaseView) mActivity, "确认送达", 3) {
            @Override
            public void onSuccessResponse(String response) {
                if (API.filterJson(response)) {
                    sendingOrderDialog.dismissDialog();
                }
            }

            @Override
            public void onErrorResponse() {
                AtyUtils.showShort(mActivity, "确认送达失败", false);
            }
        });
    }

    /**
     * 退出登录
     */
    private void LoginOut() {

        String username = (String) SpUtils.getData(mActivity, Constant.USER_NAME, "");
        String password = (String) SpUtils.getData(mActivity, Constant.USER_PWD, "");

        SpUtils.clearData(mActivity);
        SpUtils.putData(mActivity, Constant.USER_NAME, username);
        SpUtils.putData(mActivity, Constant.USER_PWD, password);
        startActivity(new Intent(mActivity, LoginActivity.class));
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == 101) {
            getTableList();

            if (messageDialog != null && !messageDialog.isShowing()) {
                if (message_list.size() > 0) {
                    String extra = message_list.get(0);
                    message_list.remove(extra);
                    showMessageDialog(extra);
                }
            }
        }
    }

    /**
     * 提示弹框
     *
     * @param extra
     */
    private void showMessageDialog(String extra) {
        JSONObject obj = JSONObject.parseObject(extra);
        String table_num = obj.getString("table_num");
        String table_tme = obj.getString("table_tme");
        String table_price = obj.getString("table_price");
        String table_count = obj.getString("table_count");
        String table_state = obj.getString("table_state");
        String table_sn = obj.getString("table_sn");
        messageDialog.showMeaageDiaog(new MainMessageBean(table_num, table_tme, table_price, table_count, table_state, table_sn));
    }

    protected LocalBroadcastManager broadcastManager;
    protected IntentFilter intentFilter;
    protected MyActivityReceiver receiver;

    /**
     * 客户消息
     */
    public static final String ACTION_RECIVE_NEWRED = "action_awaiter";

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        getTableList();
    }


    /**
     * 广播监听
     */
    public class MyActivityReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                try {
                    String action = intent.getAction();
                    String extra = intent.getStringExtra("extra");

                    if (!TextUtils.isEmpty(extra)) {
                        //桌台状态改变通知
                        if (!extra.contains("{")) {
                            area_id = extra;
                            getTableList();
                        } else {
                            JSONObject obj = JSONObject.parseObject(extra);
                            String table_state = obj.getString("table_state");
                            String table_num = obj.getString("table_num");
                            if (table_state.equals("呼叫服务员")) {
                                xunFeiUtils.playVoice(table_num + "号餐桌需要服务员帮助");
                            } else {
                                xunFeiUtils.playVoice(table_num + "号餐桌需要结账");
                            }

                            //每次收到广播消息都添加到集合，等待处理
                            message_list.add(extra);

                            if (TextUtils.equals(action, ACTION_RECIVE_NEWRED)) {
                                //如果弹框不为空并且未显示，则显示弹框并删除这条消息，
                                if (messageDialog != null && !messageDialog.isShowing()) {
                                    message_list.remove(extra);
                                    showMessageDialog(extra);
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 退出程序
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            doubleClickExit(2000, "再按一次返回键退出程序");
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        // 广播监听
        if (broadcastManager != null && receiver != null) {
            broadcastManager.unregisterReceiver(receiver);
        }

        super.onDestroy();
        messageDialog.closeHandle();

        if (xunFeiUtils != null) {
            xunFeiUtils.closeFile();
        }
    }

}
